package com.gravata.enigma;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileFilter;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.io.CopyStreamEvent;
import org.apache.commons.net.io.CopyStreamListener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.gravata.enigma.activities.TelaInicial;
import com.gravata.enigma.model.Bouquet;
import com.gravata.enigma.reader.ReloaderUtil;

@SuppressLint("DefaultLocale")
public class SendDataHelper extends AsyncTask<String, String, Boolean> {

	private Context context;
	private ProgressDialog progress;

	private static String host;
	private static  String user;
	private static  String pass;
	private static int port;
	private static FTPClient ftp = new FTPClient();
	public static final String folder = "/etc/enigma2";


	public SendDataHelper(Context context) {
		this.context=context;
		host=TelaInicial.profile.getUrl();
		user=TelaInicial.profile.getUsuario();
		pass=TelaInicial.profile.getSenha();
		port=TelaInicial.profile.getPorta();
	}


	private void delete() {
		try {

			List<FTPFile> files;
			files = Arrays.asList(ftp.listFiles(folder, new FTPFileFilter() {
				@Override
				public boolean accept(FTPFile file) {
					if (file.getName().endsWith(".tv"))
						return true;
					return false;
				}
			}));

			for (FTPFile file : files) {
				publishProgress(context.getString(R.string.ftp_apagando) +file.getName());
				ftp.deleteFile(folder+ "/"+file.getName());
			}
			publishProgress(context.getString(R.string.ftp_apagados));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	private void send(){
		publishProgress(context.getString(R.string.ftp_preparando_arquivos));
		Map<String,String> strFiles=new HashMap<String, String>();
		strFiles.put("bouquets.tv",TelaInicial.repositorioBouquets.getBouquetsTvFile(TelaInicial.profile));
		List<Bouquet> bouquets=TelaInicial.repositorioBouquets.listar(TelaInicial.profile);

		for(Bouquet bouquet :bouquets){
			strFiles.put(bouquet.getUserBouquetTv(),bouquet.getBouquetFile());
			publishProgress(bouquet.getName()+" "+context.getString(R.string.ftp_criado));
		}

		Set<String> keys=strFiles.keySet();
		for(String key: keys){

			try {
				publishProgress(context.getString(R.string.ftp_criado)+" "+key+"...");
				ftp.storeFile(folder+ "/"+key, getFile(strFiles.get(key)) );
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	private InputStream getFile(String file){
		return new ByteArrayInputStream(file.getBytes());
	}

	@Override
	protected Boolean doInBackground(String... arg0) {

		try{
			// Connect to the SERVER
			ftp.connect(host, port);
			if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
				publishProgress(context.getString(R.string.ftp_error_conexao));
				Thread.sleep(3000);
				return false;
			}

			// Login to the SERVER
			ftp.enterLocalPassiveMode();
			if (!ftp.login(user, pass)) {
				publishProgress(context.getString(R.string.ftp_error_login));
				Thread.sleep(3000);
				return false;
			}
			}catch(Exception e){
				e.printStackTrace();
			}

			ftp.setCopyStreamListener(createListener());
			publishProgress(context.getString(R.string.ftp_conectado));

		delete();
		send();
		disconnect();
		updateReceive();
		publishProgress(context.getString(R.string.ftp_pronto));
		return true;
	}

	private void disconnect(){
		try {
			ftp.logout();
			ftp.disconnect();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void updateReceive(){
		publishProgress(context.getString(R.string.ftp_atualizando_lista));
		try {
			if(!ReloaderUtil.reload(context)){
				publishProgress(context.getString(R.string.ftp_error_atualizar_lista));
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onPreExecute() {
		progress = new ProgressDialog((Activity) context);
		// Cria novo um ProgressDialogo e exibe
		progress.setMessage(context.getString(R.string.ftp_conectando));
		progress.setCancelable(false);
		progress.show();

	}

	@Override
	protected void onProgressUpdate(String... values) {
		// Atualiza mensagem
		if (progress != null)
			progress.setMessage(values[0]);
	}

	@Override
	protected void onPostExecute(Boolean result) {

		progress.dismiss();
	}

	  private CopyStreamListener createListener(){
	        return new CopyStreamListener(){
	            private long megsTotal = 0;
//	            @Override
	            public void bytesTransferred(CopyStreamEvent event) {
	                bytesTransferred(event.getTotalBytesTransferred(), event.getBytesTransferred(), event.getStreamSize());
	            }

//	            @Override
	            public void bytesTransferred(long totalBytesTransferred,
	                    int bytesTransferred, long streamSize) {
	                long megs = totalBytesTransferred / 1000000;
	                for (long l = megsTotal; l < megs; l++) {
	                    System.err.print("#");
	                }
	                megsTotal = megs;
	            }
	        };
	    }

}
